import 'package:flutter/material.dart';
import 'package:flutter_1911/dao/travel_dao.dart';
import 'package:flutter_1911/model/travel_model.dart';
import 'package:flutter_1911/widget/webview.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

const _TRAVEL_URL =
    'https://m.ctrip.com/restapi/soa2/16189/json/searchTripShootListForHomePageV2?_fxpcqlniredt=09031014111431397988&__gw_appid=99999999&__gw_ver=1.0&__gw_from=10650013707&__gw_platform=H5';
const PAGE_SIZE = 10;
class TravelTabPage extends StatefulWidget {
  final String travelUrl ;
  final String groupChannelCode;

  const TravelTabPage({Key? key, this.travelUrl = _TRAVEL_URL, required this.groupChannelCode }) : super(key: key);

  @override
  _TravelTabPageState createState() => _TravelTabPageState();
}

class _TravelTabPageState extends State<TravelTabPage> with AutomaticKeepAliveClientMixin{
  List<TravelItem>? travelItems = [];
  int pageIndex = 1;

  @override
  void initState() {
    _loadData();
    super.initState();
  }
  @override
  void dispose() {
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: travelItems == null ? Text('加载中。。'):MasonryGridView.count(
        crossAxisCount: 2,
        mainAxisSpacing: 2,
        crossAxisSpacing: 2,
        itemCount: travelItems!.length, itemBuilder: (context, index) {
          return _TravelItem(
            index: index,
            item: travelItems![index],
          );
        },
      ),
    );
  }
  void _loadData() {
    TravelDao.fetch(widget.travelUrl, widget.groupChannelCode, pageIndex, PAGE_SIZE)
        .then((value) {
          setState(() {
            List<TravelItem>? items = _filterItems(value.resultList!);
        if(travelItems != null){
              travelItems?.addAll(items!);
            }else{
              travelItems = items;
            }
          });
    }).catchError((e){
      print(e);
    });
  }

  List<TravelItem>? _filterItems(List<TravelItem> resultList) {
    if(resultList == null){
      return [];
    }
    List<TravelItem> filterItems = [];
    resultList.forEach((element) {
      if(element.article != null){
        //移除article为空的模型
        filterItems.add(element);
      }
    });
    return filterItems;
  }
  @override
  bool get wantKeepAlive => true;
}
 class _TravelItem extends StatelessWidget {
  final TravelItem item;
  final int index;
   const _TravelItem({Key? key,required this.item, required this.index}) : super(key: key);

   @override
   Widget build(BuildContext context) {
     return GestureDetector(
       onTap: (){
         if(item.article.urls!=null && item.article.urls.isNotEmpty){
           Navigator.push(context, MaterialPageRoute(builder: (context)=>
               HiWebView(
                 url: item.article.urls[0].h5Url,
                 title:'详情',
               )
           ));
         }
       },
       child: Card(
         child: PhysicalModel(
           color: Colors.transparent,
           clipBehavior: Clip.antiAlias,
           borderRadius: BorderRadius.circular(5),
           child: Column(
             crossAxisAlignment: CrossAxisAlignment.start,
             children: [
               _itemImage(),
               Container(
                 padding: const EdgeInsets.all(2),
                 child: Text(
                   item.article.articleTitle,
                   maxLines: 2,
                   overflow: TextOverflow.ellipsis,
                   style: const TextStyle(fontSize: 14, color: Colors.black87),
                 ),
               ),
               _infoText(),
             ],
           ),
         ),
       ),
     );
   }
   //实现图片的叠加
   _itemImage(){
     //设置 stack
     return Stack(
       children: [
         Image.network(item.article.images[0].dynamicUrl),
         Positioned(
           bottom: 8,
           left: 8,
             child: Container(
               padding: const EdgeInsets.fromLTRB(5, 1, 5, 1),
               decoration: BoxDecoration(
                 color: Colors.black54,
                 borderRadius: BorderRadius.circular(10)
               ),
               child: Row(
                 children: [
                   const Padding(
                     padding: EdgeInsets.only(right: 3),
                     child: Icon(
                       Icons.location_on,
                       color: Colors.white,
                       size: 12,
                     ),
                   ),
                   LimitedBox(
                     maxWidth: 130,
                     child: Text(
                       _poiName(),
                       maxLines: 1,
                       overflow: TextOverflow.ellipsis,
                       style: const TextStyle(color: Colors.white, fontSize: 12),
                     ),
                   )
                 ],
               ),
             ),
         )
       ],
     );
   }
  String _poiName() {
     return item.article.pois==null || item.article.pois?.length==0 ? '未知' : item.article.pois?[0]!.poiName ?? '未知';
  }

  _infoText() {
     return Container(
       padding: const EdgeInsets.fromLTRB(5, 0, 5, 9),
       child: Row(
         mainAxisAlignment: MainAxisAlignment.spaceBetween,
         children: [
           Row(
             children: [
               PhysicalModel(color: Colors.transparent,
                 clipBehavior: Clip.antiAlias,
                 borderRadius: BorderRadius.circular(12),
                 child: Image.network(item.article.author!.coverImage!.dynamicUrl, width: 24, height: 24,),
               ),
               Container(
                 padding: const EdgeInsets.all(5),
                 width: 90,
                 child: Text(item.article.author!.nickName, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 12),),
               )
             ],
           ),
           //设置旅拍item的点赞
           Row(
             children: [
               const Icon(Icons.thumb_up, size: 14, color: Colors.grey,),
               Padding(padding: const EdgeInsets.only(left: 3),
                 child: Text(item.article.likeCount.toString(), style: const TextStyle(fontSize: 10),),
               )
             ],
           )
         ],
       ),
     );
  }
 }






